<template>
  <drag-modal
    title="修改密码"
    :width="360"
    :visible="visible"
    :centered="true"
    :destroyOnClose="true"
    :confirmLoading="submitLoading"
    :maskClosable="false"
    @ok="ok"
    @cancel="cancel"
  >
    <a-spin :spinning="loading">
      <a-form-model :model="form" ref="form" :label-col="{span: 5}" :wrapperCol="{span: 16, offset: 1}">
        <div class="fold">
          <a-form-model-item
            label="旧密码"
            prop="oldPassword"
            required
          >
            <a-input allowClear type="password" v-model="form.oldPassword" />
          </a-form-model-item>
          <a-form-model-item
            label="新密码"
            prop="newPassword"
            required
          >
            <a-input allowClear type="password" v-model="form.newPassword" />
          </a-form-model-item>
        </div>
      </a-form-model>
    </a-spin>
  </drag-modal>
</template>

<script>
import {accountService} from '@/services'

export default {
  name: 'ChangePasswordModal',
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      loading: false,
      submitLoading: false,
      form: {
        oldPassword: undefined,
        newPassword: undefined
      }
    }
  },
  methods: {
    cancel() {
      this.$emit('cancel')
    },
    ok() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          let params = {
            oldPassword: this.$md5(this.form.oldPassword),
            newPassword: this.$md5(this.form.newPassword)
          }
          accountService.changePassword(JSON.stringify(params)).then(res => {
            const result = res.data
            if (result.code === 200) {
              this.$emit('ok')
            }
          }).finally(this.submitLoading = false)
        }
      })
    }
  }
}
</script>
